package com.wframe.project.jnd.rest.util;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.frame.pageform.component.JsonObject;

public class JsonReturn {

    private DynamicCodeEnum msgCode;
    private JsonObject jsonobj = new JsonObject();
    private Object returnObj;

    public JsonReturn() {
    }

    public JsonReturn(CodeEnum code) {
        this.msgCode = new DynamicCodeEnum(code.getCode(), code.getName());
    }

    public void putData(Object obj) {
        this.returnObj = obj;
    }

    public void setMsgCode(CodeEnum code) {
        if (this.msgCode == null) msgCode = new DynamicCodeEnum(code.getCode(), code.getName());
        else {
            msgCode.setCode(code.getCode());
            msgCode.setName(code.getName());
        }
    }

    public void setMsgCode(DynamicCodeEnum code) {
        this.msgCode = code;
    }

    public String toString() {
        if (msgCode == null) setMsgCode(CodeEnum.Ok);
        jsonobj.put("MsgCode", msgCode.getCode());
        jsonobj.put("MsgDesc", msgCode.getName());
        jsonobj.put("Data", returnObj);
        String s = jsonobj.toString().replace(jsonobj.JSONDATA, "");
        return s;
    }

    public String toErrorString(Class cls, Exception e) {
        Exception eobj = (Exception) e.getCause();
        String msg = e.getMessage();
        if (eobj != null) {
            msg = eobj.getMessage();
            while (eobj.getCause() != null) {
                eobj = (Exception) eobj.getCause();
                msg = eobj.getMessage();
            }
        } else eobj = e;
        if (eobj instanceof ClientException) {
            ClientException clen = (ClientException) eobj;
            if (StringUtils.isNotBlank(clen.getCode()))
                setMsgCode(new DynamicCodeEnum(clen.getCode(), msg));
            else
                setMsgCode(new DynamicCodeEnum(CodeEnum.Err.getCode(), msg));
        } else {
            setMsgCode(new DynamicCodeEnum(CodeEnum.Err.getCode(), CodeEnum.Err.getName()));
            Logger.getLogger(cls).error("错误：", e);
        }
        return toString();
    }

    public String toString(String url) {
        this.returnObj = url;
        return toString();
    }
}
